#include <linux/init.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <linux/slab.h>
#include <asm/uaccess.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/sched.h>
#include <linux/cred.h>

#include "scull.h"

static int scull_major = SCULL_MAJOR;
static int scull_minor = SCULL_MINOR;
static int scull_nr_devs = SCULL_NR_DEVS;
static int scull_quantum = SCULL_QUANTUM;
static int scull_qset = SCULL_QSET;
static dev_t dev;
static struct scull_dev *sculldev;

/*page 175*/
static int scull_u_count;
static uid_t scull_u_owner;
static DEFINE_SPINLOCK(scull_u_lock);

module_param(scull_major, int      , S_IRUGO);
module_param(scull_nr_devs, int      , S_IRUGO);
module_param(scull_quantum, int       , S_IRUGO);
module_param(scull_qset , int     , S_IRUGO);

int scull_trim(struct scull_dev *dev)
{
	struct scull_qset *next, *dptr;
	int qset = dev->qset;
	int i;
	for (dptr = dev->data; dptr; dptr = next) {
		if (dptr->data) {
			for (i = 0; i < qset; i++) 
				kfree(dptr->data[i]);
			kfree(dptr->data);
			dptr->data = NULL;
		}
		next = dptr->next;
		kfree(dptr);
	}

	dev->size = 0;
	dev->quantum = scull_quantum;
	dev->qset = scull_qset;
	dev->data = NULL;
	return 0;
}

static struct scull_qset *scull_follow(struct scull_dev *dev, int n)
{	
	while(n--) {
		if (!dev->data->next) {
			dev->data->next = 
				kmalloc(sizeof(struct scull_qset), GFP_KERNEL);
			memset(dev->data->next, 0, sizeof(struct scull_qset));
		}
		dev->data = dev->data->next;
		continue;
	}
	return dev->data;
}

/*page175*/
static int scull_open(struct inode *inode, struct file *filp)
{
	struct scull_dev *dev;
	dev = container_of(inode->i_cdev, struct scull_dev, cdev);

	spin_lock(&scull_u_lock);
	if (scull_u_count && (scull_u_owner != current_uid().val) &&
			(scull_u_owner != current_euid().val) &&
			!capable(CAP_DAC_OVERRIDE)) {
		spin_unlock(&scull_u_lock);
		return -EBUSY;
	}
	if (scull_u_count == 0)
		scull_u_owner = current_uid().val;

	scull_u_count++;
	spin_unlock(&scull_u_lock);
	
	if ((filp->f_flags & O_ACCMODE) == O_WRONLY) {
		scull_trim(dev);
		dev->data = kmalloc(sizeof(struct scull_qset), GFP_KERNEL);
		memset(dev->data, 0, sizeof(struct scull_qset));
	}
	filp->private_data =dev;
	return 0;
}

/*page 175*/
static int scull_release(struct inode *inode, struct file *filp)
{
	spin_lock(&scull_u_lock);
	scull_u_count--;
	spin_unlock(&scull_u_lock);
	return 0;
}

static ssize_t scull_read(struct file *filp, char __user *buf, size_t count, loff_t *f_pos)
{
	struct scull_dev *dev = filp->private_data;
	struct scull_qset *dptr;
	int quantum = dev->quantum, qset = dev->qset;
	int itemsize = quantum * qset;
	int item, s_pos, q_pos, rest;
	ssize_t retval = 0;
	
	if (down_interruptible(&dev->sem))
		return -ERESTARTSYS;
	if (*f_pos >= dev->size)
		goto out;
	if (*f_pos +count > dev->size)
		count = dev->size - *f_pos;

	item = (long)*f_pos / itemsize;
	rest = (long)*f_pos %itemsize;
	s_pos = rest / quantum; q_pos = rest % quantum;

	dptr = scull_follow(dev, item);

	if (dptr == NULL || !dptr->data ||!dptr->data[s_pos])
		goto out;

	if (count > quantum - q_pos)
		count = quantum - q_pos;

	if (copy_to_user(buf, dptr->data[s_pos] + q_pos, count)) {
		retval = -EFAULT;
		goto out;
	}
	PDEBUG("read count = %lu\n", (long unsigned int)count);

	/* page84 test 
	if (printk_ratelimit())
		PDEBUG("test!!!!!!!\n");
	*/
	
	*f_pos += count;
	retval = count;
	out:
		up(&dev->sem);
		return retval;
}

static ssize_t scull_write(struct file *filp, const char __user *buf, size_t count,
			loff_t *f_pos)

{
	struct scull_dev *dev = filp->private_data;
	struct scull_qset *dptr;
	int quantum = dev->quantum, qset = dev->qset;
	int itemsize = quantum * qset;
	int item, s_pos, q_pos, rest;
	ssize_t retval = -ENOMEM;

	if (down_interruptible(&dev->sem))
		return -ERESTARTSYS;
	item = (long)*f_pos / itemsize;
	rest = (long)*f_pos % itemsize;
	s_pos = rest / quantum;
	q_pos = rest % quantum;

	dptr = scull_follow(dev, item);

	if (dptr == NULL)
		goto out;

	if (!dptr->data) {
		dptr->data = kmalloc(qset * sizeof(char *), GFP_KERNEL);
		if (!dptr->data)
			goto out;
		memset(dptr->data, 0, qset * sizeof(char *));
	}

	if (!dptr->data[s_pos]) {
		dptr->data[s_pos] = kmalloc(quantum, GFP_KERNEL);
		if (!dptr->data[s_pos])
			goto out;
	}

	if (count > quantum - q_pos)
		count = quantum - q_pos;

	if (copy_from_user(dptr->data[s_pos] + q_pos, buf, count)) {
		retval = -EFAULT;
		goto out;
	}

	*f_pos += count;
	retval = count;

	if (dev->size < *f_pos)
		dev->size = *f_pos;
	PDEBUG("size = %lu, write count = %lu\n", 
		(long unsigned int)dev->size, (long unsigned int)count);
	out:
		up(&dev->sem);
		return retval;
	
}


static long scull_ioctl (struct file *filp, unsigned int cmd, unsigned long arg)
{
	int err = 0, tmp;
	int retval = 0;

	if (_IOC_TYPE(cmd) != SCULL_IOC_MAGIC) return -ENOTTY;
	if (_IOC_NR(cmd) > SCULL_IOC_MAXNR) return -ENOTTY;

	if (_IOC_DIR(cmd) & _IOC_READ)
		err = !access_ok(/*VERIFY_WRITE,*/
			(void __user *)arg, _IOC_SIZE(cmd));
	else if (_IOC_DIR(cmd) & _IOC_WRITE)
		err = !access_ok(/*VERIFY_READ,*/
			(void __user *)arg, _IOC_SIZE(cmd));
	if (err) return -EFAULT;

	switch (cmd) {
	case SCULL_IOCRESET:
		scull_quantum = SCULL_QUANTUM;
		scull_qset = SCULL_QSET;
		PDEBUG("0--SCULL_IOCRESET:scull_quantum = %i, scull_qset = %i\n", 
				scull_quantum, scull_qset);
		break;
	case SCULL_IOCSQUANTUM:
		if (!capable(CAP_SYS_ADMIN))
			return -EPERM;
		retval = __get_user(scull_quantum, (int __user *)arg);
		PDEBUG("1--SCULL_IOCSQUANTUM:scull_quantum = %i\n", 
				scull_quantum);
		break;
	case SCULL_IOCTQUANTUM:
		if (!capable(CAP_SYS_ADMIN))
			return -EPERM;
		scull_quantum = arg;
		PDEBUG("2--SCULL_IOCTQUANTUM:scull_quantum = %i\n", 
				scull_quantum);
		break;
	case SCULL_IOCGQUANTUM:
		retval = __put_user(scull_quantum, (int __user *)arg);
		PDEBUG("3--SCULL_IOCGQUANTUM:scull_quantum = %i\n", 
				scull_quantum);
		break;
	case SCULL_IOCQQUANTUM:
		return scull_quantum;
		PDEBUG("4--SCULL_IOCQQUANTUM:scull_quantum = %i\n", 
				scull_quantum);
		break;
	case SCULL_IOCXQUANTUM:
		if (!capable(CAP_SYS_ADMIN))
			return -EPERM;
		tmp = scull_quantum;
		retval = __get_user(scull_quantum, (int __user *)arg);
		if (retval == 0)
			retval = __put_user(tmp, (int __user *)arg);
		PDEBUG("5--SCULL_IOCXQUANTUM:scull_quantum = %i\n", 
				scull_quantum);
		break;
	case SCULL_IOCHQUANTUM:
		if (!capable(CAP_SYS_ADMIN))
			return -EPERM;
		tmp = scull_quantum;
		scull_quantum = arg;
		PDEBUG("6--SCULL_IOCHQUANTUM:scull_quantum = %i\n", 
				scull_quantum);
		return tmp;
	case SCULL_IOCSQSET:
		if (!capable(CAP_SYS_ADMIN))
			return -EPERM;
		retval = __get_user(scull_qset, (int __user *)arg);
		PDEBUG("7--SCULL_IOCSQSET:scull_qset = %i\n", 
				scull_qset);
		break;
	case SCULL_IOCTQSET:
		if (!capable(CAP_SYS_ADMIN))
			return -EPERM;
		scull_qset = arg;
		PDEBUG("8--SCULL_IOCTQSET:scull_qset = %i\n", 
				scull_qset);
		break;
	case SCULL_IOCGQSET:
		retval = __put_user(scull_qset, (int __user *)arg);
		PDEBUG("9--SCULL_IOCGQSET:scull_qset = %i\n", 
				scull_qset);
		break;
	case SCULL_IOCQQSET:
		return scull_qset;
		PDEBUG("10--SCULL_IOCQQSET:scull_qset = %i\n", 
				scull_qset);
		break;
	case SCULL_IOCXQSET:
		if (!capable(CAP_SYS_ADMIN))
			return -EPERM;
		tmp = scull_qset;
		retval = __get_user(scull_qset, (int __user *)arg);
		if (retval == 0)
			retval = __put_user(tmp, (int __user *)arg);
		PDEBUG("11--SCULL_IOCXQSET:scull_qset = %i\n", 
				scull_qset);
		break;
	case SCULL_IOCHQSET:
		if (!capable(CAP_SYS_ADMIN))
			return -EPERM;
		tmp = scull_qset;
		scull_qset = arg;
		PDEBUG("12--SCULL_IOCHQSET:scull_qset = %i\n", 
				scull_qset);
		return tmp;
	default:
		return -ENOTTY;
	}
	return retval;
}

/*page172*/
static loff_t scull_llseek (struct file * filp, loff_t off, int whence)
{
	struct scull_dev *dev = filp->private_data;
	loff_t newpos;

	switch(whence) {
	case 0: /* SEEK_SET */
		newpos = off;
		break;
	case 1: /* SEEK_CUR */
		newpos = filp->f_pos + off;
		break;
	case 2: /* SEEK_END */
		newpos = dev->size + off;
		break;
	default:
		return -EINVAL;
	}
	if (newpos < 0) return -EINVAL;
	filp->f_pos = newpos;
	return newpos;
}


static struct file_operations scull_fops = {
	.owner = THIS_MODULE,
	.llseek = scull_llseek,
	.read = scull_read,
	.write = scull_write,
	.unlocked_ioctl = scull_ioctl,
	.open = scull_open,
	.release = scull_release,
};

/*
* Assigned dev number.
*/
static int scull_register_chrdev(void)
{
	int result;
	if (scull_major) {
		dev = MKDEV(scull_major, scull_minor);
		result = register_chrdev_region(dev, scull_nr_devs, DEVNAME);
	} else {
		result = alloc_chrdev_region(&dev, scull_minor, scull_nr_devs, 
					     DEVNAME);
		scull_major = MAJOR(dev);
	}
	
	return result;
}

/*
* Scull character device registration.
*/
static void scull_setup_cdev(struct scull_dev *dev, int index)
{
	int err, devno = MKDEV(scull_major, scull_minor + index);
	cdev_init(&dev->cdev, &scull_fops);
	dev->cdev.owner = THIS_MODULE;
	dev->cdev.ops = &scull_fops;
	err = cdev_add(&dev->cdev, devno, 1);
	if (err)
		printk(KERN_WARNING "Error %d adding scull%d", err, index);
}


static void scull_exit(void)
{
	int i; 

	if (sculldev) {
		for (i = 0; i < scull_nr_devs; i++) {
			scull_trim(&sculldev[i]);
			cdev_del(&sculldev[i].cdev);
		}
		kfree(sculldev);
	}

	unregister_chrdev_region(dev, scull_nr_devs);
}

static int __init scull_init(void)
{
	int result = 0;
	int i;

	result = scull_register_chrdev();
	if (result < 0) {
		printk(KERN_WARNING "scull: can't get major %d\n", scull_major);
		return result;
	}

	PDEBUG("Get dev major number = %d\n", scull_major);

	sculldev = kmalloc(scull_nr_devs * sizeof(struct scull_dev), GFP_KERNEL);
	if (!sculldev) {
		result = -ENOMEM;
		goto fail;
	}

	for (i = 0; i < scull_nr_devs; i++) {

		sculldev[i].data = kmalloc(sizeof(struct scull_qset), GFP_KERNEL);
		memset(sculldev[i].data, 0, sizeof(struct scull_qset));
		sculldev[i].quantum = scull_quantum;
		sculldev[i].qset = scull_qset;
		sculldev[i].size = 0;
		sculldev[i].access_key = 0;
		sema_init(&sculldev[i].sem, 1);
		scull_setup_cdev(&sculldev[i], i);
	}


fail:
	if (result)
		scull_exit();	
	return result;
	
}

module_init(scull_init);
module_exit(scull_exit);

MODULE_LICENSE("GPL");
MODULE_VERSION("v1.0");
MODULE_AUTHOR("LiuGuiChao");
MODULE_DESCRIPTION("A test moudle!");

